package com.app.core.web.filter;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.session.UserSession;
import com.app.core.web.context.RequestContext;
import com.app.core.web.util.AppContextUtil;
import com.guda.mp.entity.SysLog;
import com.guda.mp.service.SysLogService;

public class SysLogInterceptor implements HandlerInterceptor {
	private static final Logger log = LoggerFactory.getLogger(SysLogInterceptor.class);

	public static final HashMap<String, JSONObject> LOG_MAP = new HashMap<>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		String contextPath = request.getContextPath();
		String requestURI = request.getRequestURI();
		requestURI = requestURI.substring(contextPath.length(), requestURI.length());
		requestURI = requestURI.split("\\?")[0];

		if (LOG_MAP.containsKey(requestURI)) {
			SysLogService logService = (SysLogService) AppContextUtil.getContext().getBean("sysLogServiceImpl");
			UserSession loginUser = RequestContext.getUserSession();
			SysLog sysLog = new SysLog();
			JSONObject jsonObject = LOG_MAP.get(requestURI);
			sysLog.setModule(jsonObject.getString("module"));
			sysLog.setOprType(jsonObject.getString("oprType"));
			sysLog.setOprName(jsonObject.getString("oprName"));
			if ("登录".equals(sysLog.getOprType())) {
				sysLog.setUserName(request.getParameter("loginName").toString());
			} else {
				sysLog.setUserName(loginUser.getLoginName());
				sysLog.setUserId(loginUser.getUserId());
			}
			sysLog.setUrl(request.getRequestURI());
			sysLog.setOprTime(new Date());

			String idName = jsonObject.getString("idName");
			idName = (idName == null) ? "id" : idName;

			sysLog.setDataId(request.getParameter(idName));
			sysLog.setInParams(JSON.toJSONString(request.getParameterMap()));
			sysLog.setCreateTime(new Date());
			sysLog.setCreateTime(new Date());
			logService.add(sysLog);
		}
	}

}
